/**
 * 关联表 动态表格混入
 */
import { post } from '@/utils/request'
export default {
  props: {
    isDialog: {
      type: Boolean,
      default: false
    },
    mainId: {
      type: [String, Number],
      default: ''
    },
    mainMarkId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isSave: false,
      saveMarkId: '',
      disabledSave: false,
      editCols: [],
      dbEdit: false
    }
  },
  computed: {
    reComputedDataSource() {
      return { dataSource: this.dataSource }
    }
  },
  watch: {
    // 防止分页问题
    page() {
      this.cancelRowSave()
    },
    // 防止分页问题
    size() {
      this.cancelRowSave()
    },
    mainId: {
      handler(val) {
        if (!this.isDialog) {
          if (val) {
            this.handleSearchByMainId()
          } else {
            this.dataSource = []
            this.handleSetCancelStatus()
          }
        }
      },
      immediate: true
    },
    isDialog: {
      handler(val) {
        if (val) {
          this.handleSearchByMainId()
        }
      },
      immediate: true
    }
  },
  methods: {
    /**
     * dialog => true => search
     */
    handleSearchByMainId() {
      this.searchForm[this.mainMarkId] = this.mainId
      this.handleSearchClick()
    },
    /**
     * 添加
     */
    handleAddRow() {
      this.handleSetSaveStatus()
      // 第一项进行添加
      this.dataSource.unshift({ operMark: 'add' })
    },
    /**
     * 修改
     */
    handleEditRow(index, id) {
      this.handleSetSaveStatus(id)
      this.$set(this.dataSource[index], 'operMark', 'edit')
    },
    /**
     * 取消
     */
    cancelRowSave() {
      const findSaveIndex = this.dataSource.findIndex((item) => ['add', 'edit'].includes(item.operMark))
      if (findSaveIndex !== -1) {
        const isAdd = this.dataSource[findSaveIndex].operMark === 'add'
        isAdd ? this.dataSource.splice(findSaveIndex, 1)
          : this.dataSource.splice(findSaveIndex, 1, JSON.parse(JSON.stringify(this.cacheDataSource[findSaveIndex])))
      }
      this.handleSetCancelStatus()
    },
    /**
     * 设置保存状态
     * @id string 保存id 是否存在
     */
    handleSetSaveStatus(id = '') {
      this.isSave = true
      this.saveMarkId = id
      this.handleBeforeSaveRow()
    },
    /**
     * 取消保存状态
     */
    handleSetCancelStatus() {
      this.isSave = false
      this.saveMarkId = ''
      this.handleSaveAfterCancelRow()
    },
    /**
     * 保存actin
     */
    handleActionSaveForm(form, idSend, callBack) {
      post(`${this.baseApi}${this.saveMarkId ? 'edit' : 'create'}`,
        { ...form, ...idSend })
        .then((res) => {
          callBack(res)
        }).finally(() => {
          this.disabledSave = false
        })
    },
    /**
     * 保存表单
     */
    handleSaveRow() {
      this.$refs.tableForm.validate((valid) => {
        if (valid) {
          const idSend = this.saveMarkId ? { [this.markId]: this.saveMarkId } : {}
          /**
           * 俩中方式
           * 添加：取第一项
           * 修改：find id
           */
          const findForm = this.saveMarkId
            ? this.dataSource.find((item) => item.id === this.saveMarkId) : this.dataSource[0]
          findForm[this.mainMarkId] = this.mainId
          this.handleBeforeSaveForm(findForm)
          this.disabledSave = true
          this.handleActionSaveForm(findForm, idSend, (res) => {
            if (res.code === 200) {
              this.$message.success(!this.saveMarkId ? '添加成功' : '编辑成功')
              this.formVisible = false
              this.handleSetCancelStatus()
              this.handleGetTable()
            }
          })
        }
      })
    },
    /**
     * 双击编辑 只做input标记编辑 其他后续添加
     * @param {object} row 当前行
     * @param {object} column 行配置
     * @param {HTMLELEMNT} cell 行元素
     */
    tableDbEdit(row, column, cell) {
      const property = column.property
      if (this.editCols.includes(property) && !this.isSave) {
        // 当前为行内编辑操作 不允许 新增 删除 编辑
        this.dbEdit = true
        this.$set(row, `dbEdit${property}`, true)
        // 可能存在副作用 命名规范严格
        typeof this[`handleAdd${property}Effect`] === 'function' &&
          this[`handleAdd${property}Effect`](row, this.reComputedDataSource.dataSource.findIndex((item) => item.id === row.id))
        this.$nextTick(() => {
          const wrapper = cell.querySelectorAll('.el-form-item')[0]
          const input = wrapper.getElementsByTagName('input')[0]
          input.focus()
        })
      }
    },
    /**
     * 双击行内编辑blur
     * @param {object} row 当前行值
     * @param {string} property 行标记
     * @param {any} val 值 target.value
     * @param {function} effect 副作用 注：可能存在watch可能 必须返回一个需要修改的对象
     */
    handleEditForBlur(row, property, val, effect) {
      if (row[`dbEdit${property}`]) {
        const effectObj = typeof effect === 'function' ? effect() : {}
        post(`${this.baseApi}edit`,
          { [property]: val, [this.markId]: row.id, ...effectObj })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success('编辑成功')
              this.handleGetTable()
            }
          }).finally(() => {
            this.dbEdit = false
            this.$set(row, `dbEdit${property}`, false)
          })
      }
    },
    /**
     * 获取当前操作行index
     */
    handleGetOperIndex() {
      return this.saveMarkId
        ? this.dataSource.findIndex((item) => item.id === this.saveMarkId) : 0
    },
    /**
     * 打开之前
     */
    handleBeforeSaveRow() {},
    /**
     * 关闭之后
     */
    handleSaveAfterCancelRow() {},
    /**
     * 保存表单之前
     */
    handleBeforeSaveForm() {}
  }
}
